package com.lyl.serviceedu.controller.api;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyl.commonutils.JwtUtils;
import com.lyl.commonutils.R;
import com.lyl.serviceedu.cloudclient.UcenterClient;
import com.lyl.serviceedu.entity.Comment;
import com.lyl.serviceedu.service.CommentService;
import com.lyl.vo.order.UcenterMemberWebVoOrder;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-06-25
 */
@RestController
@RequestMapping("/serviceedu/api/comment")
public class CommentApiController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private UcenterClient ucenterClient;
    //根据课程id查询评论列表
    @ApiOperation(value = "评论分页列表")
    @PostMapping("/{page}/{limit}/{courseId}")
    public R getComment(@PathVariable("page") Long page,@PathVariable("limit") Long limit,@PathVariable("courseId") Long courseId){
        Page<Comment> pageParam = new Page<>(page, limit);

        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc(true,"gmt_create");
        wrapper.eq("course_id",courseId);

        commentService.page(pageParam,wrapper);
        List<Comment> commentList = pageParam.getRecords();

        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }





    @ApiOperation(value = "添加评论")
    @PostMapping("auth/save")
    public R save(@RequestBody Comment comment, HttpServletRequest request) {
        Long memberId = Long.parseLong(JwtUtils.getMemberIdByJwtToken(request,"id"));
        if(StringUtils.isEmpty(memberId)) {
            return R.error().code(28004).message("请登录");
        }
        comment.setMemberId(memberId);

        UcenterMemberWebVoOrder ucenterInfo = ucenterClient.getInfo(memberId);

        comment.setNickname(ucenterInfo.getNickname());
        comment.setAvatar(ucenterInfo.getAvatar());


        System.out.println("添加评论:" + comment);
        commentService.save(comment);
        return R.ok();
    }
}

